﻿using AuthCenter.API.Application.Command.Menu;
using AuthCenter.API.DTOs;
using AuthCenter.Domain.Menu;
using AuthCenter.ErrorCode;
using AuthCenter.Intertructrue.Interface;
using AutoMapper;
using MediatR;

namespace AuthCenter.API.Application.Handler.Menu
{
    public class GetMenuHandler : IRequestHandler<GetMenuCommand, APIResult<List<MenuDTO>>>
    {
        private readonly IBaseRepository<MenuModel> menuRepo;
        private readonly IMapper mapper;

        public GetMenuHandler(IBaseRepository<MenuModel> menuRepo,
                              IMapper mapper)
        {
            this.menuRepo = menuRepo;
            this.mapper = mapper;
        }
        public Task<APIResult<List<MenuDTO>>> Handle(GetMenuCommand request, CancellationToken cancellationToken)
        {
            APIResult<List<MenuDTO>> result = new APIResult<List<MenuDTO>>();
            var menu = menuRepo.GetAll().Where(x => x.IsDel == false).ToList();
            var list = mapper.Map<List<MenuDTO>>(menu);
            foreach (var item in list)
            {
                if(item.ParentId == 0)
                {
                    item.ParentName = "---";
                }
                else
                {
                    item.ParentName = menuRepo.GetAll().FirstOrDefault(x => x.Id == item.ParentId).MenuName;
                }
            }
            result.Message = "显示菜单成功";
            result.Code = APIEnum.Ok;
            result.Data = list.OrderByDescending(x=>x.CreateDate).ToList();
            return Task.FromResult(result);
        }
    }
}
